<template>
	<div>
  <el-dialog width="40%"  center :visible.sync="visible" :title="dataForm.isAdd ? $t('add') : $t('update')" :close-on-click-modal="true" :close-on-press-escape="true" >
    <el-form class="redisDetailForm" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="110px" >
		
		<el-form-item prop="cacheMapKey" :label="$t('redis.cacheMapKey')" >
			<el-link :underline="false">{{ dataForm.cacheMapKey }}</el-link>
		</el-form-item>
		
		<el-form-item prop="cacheMapRemark" :label="$t('redis.cacheMapRemark')" >
			<el-link :underline="false">{{ dataForm.cacheMapRemark }}</el-link>
		</el-form-item>
		
		<el-form-item prop="key" :label="$t('redis.key')" >
			<el-input size="mini" v-model="dataForm.key" :placeholder="$t('redis.key')" :disabled="true"></el-input>
		</el-form-item>
		
		<el-form-item prop="type" :label="$t('redis.type')" :disabled="true" >
			<ren-select :sDisabled="true" size="mini" v-model="dataForm.type" paramCode="redis_key_type" :placeholder="$t('redis.type')"></ren-select>
		</el-form-item>
		
		<el-form-item prop="ttl" v-if="!dataForm.isAdd" :label="$t('redis.ttl')" >
			<el-input-number size="mini" v-model="dataForm.ttl" :min="-1" :max="999999999" :label="$t('redis.ttl')"></el-input-number>
			<el-button  icon="el-icon-refresh-right" size="mini" style="margin-left: 10px;"  type="text" @click="getTTL(dataForm.key)">{{ $t('refresh') }}</el-button>
			<el-button v-if="$hasPermission('redis:modifyTTL')" icon="el-icon-edit" size="mini" style="margin-left: 10px;"  type="text" @click="modifyTTL(dataForm.key)">{{ $t('update') }}</el-button>
		</el-form-item>
		
		<el-form-item prop="index" v-if="!dataForm.isAdd && dataForm.type !== 'string'" :label="$t('redis.index')" >
			<el-input-number :disabled="true" size="mini" v-model="dataForm.index" :min="0"  :label="$t('redis.index')"></el-input-number>
		</el-form-item>
		
		<!-- add list -->
		<el-form-item prop="isLeft" v-if="dataForm.isAdd && dataForm.type === 'list'" :label="$t('redis.isLeft')" size="mini">
			<el-radio-group size="mini"  v-model="dataForm.isLeft">
				<el-radio :label="true">{{ $t('redis.isLeft1') }}</el-radio>
				<el-radio :label="false">{{ $t('redis.isLeft0') }}</el-radio>
			</el-radio-group>
		</el-form-item>
		
		
		
		<!-- 定制化表单 -->
		<!-- hash -->
		<el-form-item prop="field" v-if="dataForm.type === 'hash'" :label="$t('redis.field')" >
			<el-input size="mini" :disabled="!dataForm.isAdd" v-model="dataForm.field" :placeholder="$t('redis.key')"></el-input>
		</el-form-item>
		<el-form-item prop="rv" v-if="dataForm.type === 'hash' || dataForm.type === 'list' || dataForm.type === 'string'" :label="$t('redis.value')" >
			<el-input size="mini" type="textarea" :rows="15" v-model="dataForm.value" ></el-input>
		</el-form-item>
		
		<!-- set -->
		<el-form-item prop="member" v-if="dataForm.type === 'set'" :label="$t('redis.member')" >
			<el-input size="mini" type="textarea" :rows="15" v-model="dataForm.member" :placeholder="$t('redis.member')"></el-input>
		</el-form-item>
		
		<!-- zset -->
		<el-form-item prop="element" v-if="dataForm.type === 'zset'" :label="$t('redis.member')" >
			<el-input size="mini" type="textarea" :rows="15" v-model="dataForm.element" :placeholder="$t('redis.member')"></el-input>
		</el-form-item>
		<el-form-item prop="score" v-if="dataForm.type === 'zset'" :label="$t('redis.score')" >
			<el-input-number  size="mini" v-model="dataForm.score"   :label="$t('redis.score')" :precision="3" :step="0.5"></el-input-number>
		</el-form-item>
		

    </el-form>
	
	
    <template slot="footer">
	  <el-button v-if="!dataForm.isAdd && $hasPermission('redis:del')" size="small" type="danger" @click="del()">{{ $t('delete') }}</el-button>
	  <el-button size="small" type="success" @click="showJson()">{{ $t('json') }}</el-button>
      <el-button v-if="dataForm.isAdd  && $hasPermission('redis:add')" size="small" type="primary" @click="dataFormSubmitHandle()">{{ $t('add') }}</el-button>
	  <el-button v-if="!dataForm.isAdd  && $hasPermission('redis:modify')" :disabled="!canModify" size="small" type="primary" @click="dataFormSubmitHandle()">{{ $t('update') }}</el-button>
	  <el-button @click="visible = false" size="small">{{ $t('cancel') }}</el-button>
    </template>
	
	
  </el-dialog>
  
  
  <jsonDialog :extendsParam="jsonObj"  v-if="jsonVisible" ref="jsonDialog" ></jsonDialog>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import {  isMobile } from '@/utils/validate'
import JsonDialog from '../../../components/json_dialog'
export default {
  data () {
    return {
      visible: false,
	  canModify: true,
      dataForm: {},
	  
	  jsonVisible: false,
	  jsonObj: {}
    }
  },
  props:{
	  extendsParam:{
		  type: Object,
		  default: false
	  }
  },
  computed: {
    dataRule () {
		
		var checkValue = (rule, value, callback) => {
			if( this.dataForm.value === undefined || this.dataForm.value === null || this.dataForm.value === '' ){
				return callback(new Error( '' ))
			}else{
				callback()
			}
		}
		
		
      return {
        key: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        ttl: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
		type: [
		  { required: true, message: this.$t('validate.required'), trigger: 'blur' }
		],
		index: [
		  { required: true, message: this.$t('validate.required'), trigger: 'blur' }
		],
		
		
		rv: [
		  { required: true,validator: checkValue, message: this.$t('validate.required'), trigger: 'blur' }
		],
		member: [
		  { required: true, message: this.$t('validate.required'), trigger: 'blur' }
		],
		field: [
		  { required: true, message: this.$t('validate.required'), trigger: 'blur' }
		],
		score: [
		  { required: true, message: this.$t('validate.required'), trigger: 'blur' }
		],
		element: [
		  { required: true, message: this.$t('validate.required'), trigger: 'blur' }
		],
		
      }
    }
  },
  components: {
	  JsonDialog
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
		this.getInfo()
      })
    },
    // 获取信息
    getInfo () {
		var tt =this.extendsParam;
		this.dataForm = tt;
		if( tt.type === 'set' || tt.type === 'zset'){
			this.canModify = false
		}else{
			this.canModify = true
		}
	},
	modifyTTL( key ){
		var p = {}
		p.key = key;
		p.ttl = this.dataForm.ttl;
		this.$http['post']('/pc/redis/modifyTTL', p).then(({ data: res }) => {
		  if (res.code !== 200) {
		    return this.$message.error(res.msg)
		  }else if( res.data === 1 ){
			  this.$emit('refreshDataList')
			return this.$message.success("修改TTL"+res.msg)
		  }else{
			 return this.$message.error('修改TTL失败')
		  }
		}).catch(() => {})
	},
	getTTL( rkey ){
		var p = { params:{ key: rkey } }
		this.$http.get('/pc/redis/get',p).then(({ data: res }) => {
		  if (res.code !== 200) {
		    this.$message.error(res.msg);
			return;
		  }else{
			  this.$message.success("获取TTL"+res.msg);
			  this.dataForm.ttl = res.data.ttl;
			  this.$emit('refreshDataList')
		  }
		}).catch(() => {})
	},
	del(){
		this.$confirm('此操作将永久删除该缓存子项, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'error'
		}).then(() => {
			var p = {
				key: this.dataForm.key,
				type: this.dataForm.type,
				index: this.dataForm.index
			}
			
			if( p.type === 'hash' ){
				p.value = this.dataForm.field;
			}else if( p.type === 'set' ){
				p.value = this.dataForm.member
			}else if( p.type === 'zset'){
				p.value = this.dataForm.element
			}else if( p.type === 'list' || p.type === 'string'){
				p.value = this.dataForm.value
			}
			
			this.$http.post('/pc/redis/del',p).then(({ data: res }) => {
				if (res.code !== 200) {
					return this.$message.error(res.msg);
				}
				if( res.data > 0 )  {
					this.$message({
					  message: this.$t('delete')  + res.msg,
					  type: 'success',
					  duration: 500,
					  onClose: () => {
					    this.visible = false
						if( p.type === 'string' ){
							this.$emit('refreshStr')
						}else{
							this.$emit('refreshDataList')	
						}
					  }
					})
				}else{
					return this.$message.error("该缓存不存在或删除失败~");
				}
			}).catch(() => {});
		}).catch(() => {
			this.$message({
				type: 'info',
				message: '已取消删除'
			});          
		});
	}
	
	,showJson(){
		var p = {};
		p.type = this.dataForm.type;
		if( p.type === 'hash' ){
			p.value = this.dataForm.field;
		}else if( p.type === 'set' ){
			p.value = this.dataForm.member
		}else if( p.type === 'zset'){
			p.value = this.dataForm.element
		}else if( p.type === 'list' || p.type === 'string'){
			p.value = this.dataForm.value
		}
		
		//深拷贝
		var ttt = JSON.parse(JSON.stringify(p))
		this.jsonObj = ttt;
		this.jsonVisible = true;
		this.$nextTick(() => {
		  this.$refs.jsonDialog.init()
		})
	}
	
    // 表单提交
    ,dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
		// console.log("data:" + JSON.stringify(this.dataForm))
		var url = this.dataForm.isAdd ? '/pc/redis/add' : '/pc/redis/modify';
        this.$http['post'](url, {
          ...this.dataForm,
        }).then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">

.redisDetailForm label {
	line-height: 28px
}

</style>
